﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using Xlit.Example.Data;
using Xlit.ORM.EfCore;
using Xlit.Project.Data;
using Xlit.Standard;
using Xlit.Standard.Data;
using Xlit.Utility;

namespace Xlit.Example.Business.IOC
{
    public class DefaultModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var assemblys = AssemblyUtil.GetAllAssemblies().ToArray();
            var baseType = typeof(IDependency);

            // 事务切面 AOP
            builder.Register(c => new TransactionalInterceptor())
                .InstancePerLifetimeScope()
                .PropertiesAutowired();
            // 注册 UnitOfWork
            builder.RegisterType<EfTransaction>()
                .As<ITransaction>()
                .InstancePerLifetimeScope()
                .PropertiesAutowired();
            // 注册 DbContext
            builder.RegisterType<ExampleDbContext>()
                .As<DbContext>()
                .InstancePerLifetimeScope();
            // 注册 Repotitory
            builder.RegisterGeneric(typeof(EfRepository<,>))
                .As(typeof(IRepository<,>))
                .InstancePerLifetimeScope();
            // 注册 Serivce, Controller 等
            builder.RegisterAssemblyTypes(assemblys.ToArray())
                .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                .InstancePerLifetimeScope()
                .EnableClassInterceptors()
                .PropertiesAutowired();
        }
    }
}
